#include "RingQueue.hpp"

int cnt = 0;
pthread_mutex_t  mutex = PTHREAD_MUTEX_INITIALIZER;
void *producer(void *arg){
    RingQueue<int> *q = (RingQueue<int> *)arg;

    while (1){
        pthread_mutex_lock(&mutex);
        cnt++;
        pthread_mutex_unlock(&mutex);

        q->Push(cnt);

        pthread_mutex_lock(&mutex);
        cout << "pthread：" << gettid() << "，生产者生产：" << cnt << endl;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return nullptr;
}

void *consumer(void *arg){
    RingQueue<int> *q = (RingQueue<int> *)arg;
    while (1){
        int res =  q->Pop();
        
        pthread_mutex_lock(&mutex);
        cout << "pthread：" << gettid() << "，消费者消费：" << res << endl;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return nullptr;
}

int main(){
    RingQueue<int> q(10);
    pthread_t p[3], c[5];

    

    for ( int i = 0; i < 5; i++){
        pthread_create(&p[i], NULL, producer, &q);
    }
    for ( int i = 0; i < 3; i++){
        pthread_create(&c[i], NULL, consumer, &q);  // 消费
    }



    for (int  i = 0; i < 5; i++){
         pthread_join(p[i], NULL);
    }
    for (int  i = 0; i < 3; i++){
         pthread_join(c[i], NULL);
    }


    return 0;
}